package com.seven.sevenchat.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.seven.sevenchat.VO.TeamUserVO;
import com.seven.sevenchat.common.BaseResponse;
import com.seven.sevenchat.common.ErrorCode;
import com.seven.sevenchat.common.ResultUtils;
import com.seven.sevenchat.exception.BusinessException;
import com.seven.sevenchat.model.Team;
import com.seven.sevenchat.model.User;
import com.seven.sevenchat.model.UserTeam;
import com.seven.sevenchat.model.dto.TeamQuery;
import com.seven.sevenchat.model.request.*;
import com.seven.sevenchat.service.TeamService;
import com.seven.sevenchat.service.UserService;
import com.seven.sevenchat.service.UserTeamService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;


/**
 * 队伍接口
 */
@RestController
@RequestMapping("/team")
@CrossOrigin(origins = {"http://localhost:5173/"}) //  这里最好还是用localhost
@Slf4j
public class TeamController {

    @Resource
    private UserService userService;
    @Resource
    private RedisTemplate redisTemplate;
    @Resource
    private TeamService teamService;
    @Resource
    private UserTeamService userTeamService;

    /**
     * 队伍新增
     * @param teamAddRequest,request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTeam(@RequestBody TeamAddRequest teamAddRequest, HttpServletRequest request){
        if (teamAddRequest == null || request == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        User logininUser = userService.getLogininUser(request);//核心1
        Team team = new Team();
        BeanUtils.copyProperties(teamAddRequest,team);//核心2
        long teamId = teamService.addTeam(team,logininUser);//核心3
        return ResultUtils.success(teamId);
    }

    /**
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTeam(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request){
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        long id = deleteRequest.getId();
        User loginUser = userService.getLogininUser(request);
        boolean result = teamService.deleteTeam(id, loginUser);
        if (!result) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 队伍更改
     * @param team
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTeam(@RequestBody TeamUpdateRequest team, HttpServletRequest request){
        if (team == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User logininUser = userService.getLogininUser(request);//核心1
        boolean result = teamService.updateTeam(team,logininUser);//核心2
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"更新失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 根据Id获取队伍
     * @param id
     * @return
     */
    @GetMapping("/get")
    public BaseResponse<Team> getTeamById(long id){
        if (id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = teamService.getById(id);
        if (team == null){
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        return ResultUtils.success(team);
    }

    /**
     * 查询队伍
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list")
    public BaseResponse<List<TeamUserVO>> listTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {throw new BusinessException(ErrorCode.PARAMS_ERROR);}
        boolean isAdmin = userService.isAdmin(request);
        //查队伍
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery, isAdmin);//核心1
        final List<Long> teamIdList = teamList.stream().map(TeamUserVO::getId).collect(Collectors.toList());//核心2
        //判断当前用户是否入队
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        try {
            User loginUser = userService.getLogininUser(request);//核心3
            userTeamQueryWrapper.eq("userId", loginUser.getId());//核心4
            userTeamQueryWrapper.in("teamId", teamIdList);//核心5
            List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);//核心6
            // 已加入的队伍 id 集合
            Set<Long> hasJoinTeamIdSet = userTeamList.stream().map(UserTeam::getTeamId).collect(Collectors.toSet());//核心7
            teamList.forEach(team -> {
                boolean hasJoin = hasJoinTeamIdSet.contains(team.getId());
                team.setHasJoin(hasJoin);
            });//核心8
        } catch (Exception e) {
        }
        QueryWrapper<UserTeam> userTeamJoinQueryWrapper = new QueryWrapper<>();
        userTeamJoinQueryWrapper.in("teamId", teamIdList);//核心9
        List<UserTeam> userTeamList = userTeamService.list(userTeamJoinQueryWrapper);//核心10
        // 队伍 id => 加入这个队伍的用户列表
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(UserTeam::getTeamId));
        teamList.forEach(team -> team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(), new ArrayList<>()).size()));
        return ResultUtils.success(teamList);
    }

    /**
     * 分页列出队伍
     * @param teamQuery
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<Team>> listPageTeams(TeamQuery teamQuery) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team team = new Team();
        BeanUtils.copyProperties(teamQuery, team);
        Page<Team> page = new Page<>(teamQuery.getPageNum(),teamQuery.getPageSize());
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>(team);
        Page<Team> resultPage = teamService.page(page,queryWrapper);
        return ResultUtils.success(resultPage);
    }

    /**
     * 加入队伍
     * @param team
     * @param request
     * @return
     */
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTeam(@RequestBody TeamJoinRequest team, HttpServletRequest request){
        if (team == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User joinUser = userService.getLogininUser(request);
        boolean result = teamService.joinTeam(team,joinUser);
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"入队失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 退出队伍
     * @param team
     * @param request
     * @return
     */
    @PostMapping("/quit")
    public BaseResponse<Boolean> quitTeam(@RequestBody TeamQuitRequest team, HttpServletRequest request){
        if (team == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User joinUser = userService.getLogininUser(request);//核心1
        boolean result = teamService.quitTeam(team,joinUser);//核心2
        if (!result){
            throw new BusinessException(ErrorCode.SYSTEM_ERROR,"退队失败");
        }
        return ResultUtils.success(true);
    }

    /**
     * 列出自己创建的队伍
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/my/create")
    public BaseResponse<List<TeamUserVO>> listMyCreateTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLogininUser(request);
        boolean isAdmin = userService.isAdmin(request);
        teamQuery.setUserId(loginUser.getId());//※※※
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery,isAdmin);
        return ResultUtils.success(teamList);
    }

    /**
     * 列出自己加入的队伍
     * @param teamQuery
     * @param request
     * @return
     */
    @GetMapping("/list/my/join")
    public BaseResponse<List<TeamUserVO>> listMyJoinTeams(TeamQuery teamQuery, HttpServletRequest request) {
        if (teamQuery == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //get
        User loginUser = userService.getLogininUser(request);
        boolean isAdmin = userService.isAdmin(request);
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        List<UserTeam> userTeamList=userTeamService.list(queryWrapper);
        //重点※
        queryWrapper.eq("user_id",loginUser.getId());
        Map<Long,List<UserTeam>> listMap = userTeamList.stream()
                .collect(Collectors.groupingBy(UserTeam::getTeamId));
        List<Long> idList=new ArrayList<>(listMap.keySet());
        teamQuery.setIdList(idList);
        List<TeamUserVO> teamList = teamService.listTeams(teamQuery,true);
        return ResultUtils.success(teamList);
    }

}

